"""
用户搜索记录管理路由
提供用户搜索记录的添加和查询功能
"""

import time
from typing import Optional
from fastapi import APIRouter, Header, Query, Body
from fastapi.responses import JSONResponse
from utils.password_utils import get_user_id_from_jwt
from db.operations import UserSearchHistoryOperations
from model.message_model import Message
from model.user_search_history_model import (
    UserSearchHistory,
    SearchHistoryRequest,
    SearchHistoryListResponse,
)

# 创建用户搜索记录相关的子路由
router = APIRouter(
    prefix="/search-history",
    tags=["search-history"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="用户搜索记录管理接口信息")
async def get_search_history_info():
    """获取用户搜索记录管理接口信息和使用示例"""
    api_info = {
        "message": "用户搜索记录管理API接口",
        "endpoints": {
            "GET /api/search-history/": "获取用户搜索记录管理接口信息",
            "POST /api/search-history/add": "添加搜索记录",
            "GET /api/search-history/list": "分页获取用户搜索记录",
        },
        "examples": {
            "添加搜索记录": {
                "url": "/api/search-history/add",
                "method": "POST",
                "header": "Bearer token",
                "body": {"search_query": "Python编程"},
                "description": "记录用户搜索了'Python编程'",
            },
            "获取搜索记录": {
                "url": "/api/search-history/list?page=1&limit=10",
                "method": "GET",
                "header": "Bearer token",
                "description": "获取第1页搜索记录，每页10条",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


@router.post("/add", summary="添加搜索记录")
async def add_search_history(
    request: SearchHistoryRequest = Body(..., description="搜索记录信息"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """添加用户搜索记录"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        if not request.search_query:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="搜索关键词不能为空",
                ).model_dump(),
            )

        # 准备搜索记录数据
        search_ops = UserSearchHistoryOperations()

        search_data = UserSearchHistory(
            user_id=user_id,
            search_query=request.search_query,
        ).model_dump()

        result = await search_ops.batch_insert_search_history([search_data])

        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="搜索记录保存失败",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="搜索记录保存成功",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"保存搜索记录失败: {str(e)}",
            ).model_dump(),
        )


@router.get("/list", summary="分页获取用户搜索记录")
async def get_user_search_history(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=50, description="每页数量，最多50条"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """获取用户搜索记录列表，支持分页"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        search_ops = UserSearchHistoryOperations()

        # 获取搜索记录列表和总数
        total, search_history_list = (
            await search_ops.get_user_search_history_with_pagination(
                user_id=user_id, page=page, limit=limit
            )
        )

        # 转换为响应模型
        search_data = []
        for record in search_history_list:
            search_data.append(UserSearchHistory(**record))

        return JSONResponse(
            status_code=200,
            content=SearchHistoryListResponse(
                message="获取搜索记录成功",
                search_history_list=search_data,
                page=page,
                limit=limit,
                total=total,
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=SearchHistoryListResponse(
                message=f"获取搜索记录失败: {str(e)}",
                search_history_list=[],
                page=page,
                limit=limit,
                total=0,
            ).model_dump(),
        )
